import { userLogin } from '@/api/system/login'
import { getToken, removeToken, setToken } from '@/utils/cookie'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const userStore = defineStore('user', () => {
  const userInfo = ref({})

  function login(loginUser) {
    return new Promise((resolve, reject) => {
      userLogin(loginUser).then(response => {
        const data = response.data.data
        userInfo.value = data
        setToken(JSON.stringify(data))
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }

  function getUserInfo() {
    return new Promise(resolve => {
      let data = getToken()
      if (data) {
        data = JSON.parse(data)
        userInfo.value = data
      }
      resolve(userInfo)
    })
  }

  function logout() {
    return new Promise(resolve => {
      userInfo.value = {}
      removeToken()
      resolve(userInfo)
    })
  }

  return { userInfo, login, getUserInfo, logout }
})
